﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Text;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TheEnd
{
    public partial class FormParent : Form
    {
        // 记录当前选项卡的index
        int index = 0;
        public FormParent()
        {
            InitializeComponent();
        }
        //新建
        private void ToolStripMenuItemNew_Click(object sender, EventArgs e)
        {
            TabPage Page = new TabPage();
            Page.Name = "Page" + tabControl1.TabCount+1;
            Page.Text = "Untitled.txt";
            this.tabControl1.Controls.Add(Page);
            // 设新键的为当前页
            this.tabControl1.SelectedTab = Page;
            string formClass = "TheEnd.FormChild";
            GenerateForm(formClass, tabControl1);
            index++;
        }
        //关闭
        private void ToolStripMenuItemClose_Click(object sender, EventArgs e)
        {
            if (index > 0)
            {
                this.tabControl1.Controls.RemoveAt(this.tabControl1.SelectedIndex);
            }
            else
            {
                return;
            }
            // 设置选中的选项为删除的前一个
            this.tabControl1.SelectedIndex = --index;

        }
        //关闭全部
        private void ToolStripMenuItemCloseAll_Click(object sender, EventArgs e)
        {
            //便利父窗体的子窗体
            foreach(TabPage tabPage in tabControl1.TabPages)
            {
                foreach (Control control in tabPage.Controls)
                {
                    if (control is FormChild)
                    {
                        ((FormChild)control).Close();
                    }
                }
                tabControl1.Controls.Remove(tabPage);
            }
        }
        //退出
        private void ToolStripMenuItemExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        //在父窗体中调用当前活动子窗体的加粗事件
        private void 加粗ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormChild form = null;
            foreach (Control control in tabControl1.TabPages[tabControl1.SelectedIndex].Controls)
            {
                if (control is FormChild)
                {
                    form = (FormChild)control;
                }
            }
            form.toolStripButtonBold_Click(null, null);
        }
        //在父窗体中调用当前活动子窗体的斜体事件
        private void 斜体ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormChild form = null;
            foreach (Control control in tabControl1.TabPages[tabControl1.SelectedIndex].Controls)
            {
                if (control is FormChild)
                {
                    form = (FormChild)control;
                }
            }
            form.toolStripButtonItalic_Click(null, null);

        }
        //在父窗体中调用当前活动子窗体的保存事件 
        private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormChild form = null;
            foreach (Control control in tabControl1.TabPages[tabControl1.SelectedIndex].Controls)
            {
                if (control is FormChild)
                {
                    form = (FormChild)control;
                }
            }
            form.toolStripButtonSave_Click(null, null);
            LoadPathToList(form.saveFileDialog1.FileName);
        }
        //在父窗体中调用当前活动子窗体的保存事件
        public void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormChild form = null;
            foreach (Control control in tabControl1.TabPages[tabControl1.SelectedIndex].Controls)
            {
                if (control is FormChild)
                {
                    form = (FormChild)control;
                }
            }
            
            form.toolStripButtonOpen_Click(null, null);
            LoadPathToList(form.openFileDialog1.FileName);
            form.textBoxNode.TextChanged -= new EventHandler(form.textBoxNode_TextChanged_1);
            form.scanAll();
            form.updateRowIndex();
            form.textBoxNode.TextChanged += new EventHandler(form.textBoxNode_TextChanged_1);

        }
        private void FormParent_Load(object sender, EventArgs e)
        {
            tabControl1.Dock = DockStyle.Fill;
            InstalledFontCollection myFonts = new InstalledFontCollection();
            //获取InstalledFontCollection对象的数组
            FontFamily[] ff = myFonts.Families;
            //声明一个ArrayList变量
            ArrayList list = new ArrayList();
            //获取系统字体数组的列表中集合的长度
            int count = ff.Length;
            //使用for循环把字体写入到控件中
            for (int i = 0; i < count; i++)
            {
                string FontName = ff[i].Name;
                toolStripComboBoxFont.Items.Add(FontName);
            }
            string formClass = "TheEnd.FormChild";
            GenerateForm(formClass, tabControl1);
            InitialPathList();
        }
        //设置当前活动窗体字号
        private void toolStripComboBoxSize_TextChanged_1(object sender, EventArgs e)
        {
            FormChild form = null;
            foreach (Control control in tabControl1.TabPages[tabControl1.SelectedIndex].Controls)
            {
                if (control is FormChild)
                {
                    form = (FormChild)control;
                }
            }
            string fontName = toolStripComboBoxFont.Text;
            float fontsize = float.Parse(toolStripComboBoxSize.Text);
            form.textBoxNode.Font = new Font(fontName, fontsize);
            form.lineNumber.Font = new Font(fontName, fontsize);
        }
        //设置当前活动窗体字体
        private void toolStripComboBoxFont_TextChanged_1(object sender, EventArgs e)
        {
            FormChild form = null;
            foreach (Control control in tabControl1.TabPages[tabControl1.SelectedIndex].Controls)
            {
                if (control is FormChild)
                {
                    form = (FormChild)control;
                }
            }
            string fontName = toolStripComboBoxFont.Text;
            float fontsize = float.Parse(toolStripComboBoxSize.Text);
            form.textBoxNode.Font = new Font(fontName, fontsize);
        }

        private void 运行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
        }

        public static string Execute(string command, int seconds)
        {
            Process p = new Process();
            // 要启动的应用程序名
            p.StartInfo.FileName = "cmd.exe";
            // 禁止shell启动进程的使用
            p.StartInfo.UseShellExecute = false;
            // 重定向输入
            p.StartInfo.RedirectStandardInput = true;
            // 重定向输出 
            p.StartInfo.RedirectStandardOutput = true;
            // 重定向错误 
            p.StartInfo.RedirectStandardError = true;
            // 不再新窗口显示进程
            p.StartInfo.CreateNoWindow = true;
            // 启动
            p.Start();
            // 传递参数 
            p.StandardInput.WriteLine(command);
            // 关闭dos
            p.StandardInput.WriteLine("exit");
            // 从输出流获取结果
            String output =  p.StandardOutput.ReadToEnd();
            string errorOutput = p.StandardError.ReadToEnd();
            string[] v = output.Split('\n');
            output = "";
            for (int i = 4; i < v.Length - 3; i++)
            {
                output = output + v[i] + "\n"; 
            }
            return output+"\n"+errorOutput;
        }

        public void GenerateForm(string form, object sender)
        {
            //反射生成窗体
            Form fm = (Form)Assembly.GetExecutingAssembly().CreateInstance(form);
            //设置窗体没有边框，加入到选项卡中
            fm.FormBorderStyle = FormBorderStyle.None;
            fm.TopLevel = false;
            fm.Parent = ((TabControl)sender).SelectedTab;
            fm.ControlBox = false;
            fm.Dock = DockStyle.Fill;
            fm.Show();
        }

        private void tabPage1_Click(object sender, EventArgs e)
        {

        }

        private void 撤销ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormChild form = null;
            foreach (Control control in tabControl1.TabPages[tabControl1.SelectedIndex].Controls)
            {
                if (control is FormChild)
                {
                    form = (FormChild)control;
                }
            }
            form.撤销ToolStripMenuItem_Click(null, null);

        }

        private void 自动换行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormChild form = null;
            foreach (Control control in tabControl1.TabPages[tabControl1.SelectedIndex].Controls)
            {
                if (control is FormChild)
                {
                    form = (FormChild)control;
                }
            }
            form.自动换行_Click(null, null);
        }
        private void buttonMin_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        private void buttonMax_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Maximized;
        }

        private void buttonClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        //调整父窗体大小的时候，改变三个按钮的位置
        private void FormParent_Resize(object sender, EventArgs e)
        {
        }

        private void pythonoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormChild form = null;
            foreach (Control control in tabControl1.TabPages[tabControl1.SelectedIndex].Controls)
            {
                if (control is FormChild)
                {
                    form = (FormChild)control;
                }
            }

            if (form.Text == "SimpleIDE" && form.textBoxNode.Text == "")
            {
                MessageBox.Show("请编写内容或者打开要运行的文件!");
                return;
            }

            //如果文件已经保存，则运行
            if (form.toolStripLabelMake.Text == "")
            {
                terminal.Visible = true;
                保存ToolStripMenuItem_Click(null, null);
                terminal.Text = Execute("python " + form.Text, 10);
            }
            //如果文件还未保存，则提示用户先保存
            else
            {
                保存ToolStripMenuItem_Click(null, null);
                terminal.Visible = true;
                terminal.Text = Execute("python " + form.Text, 10);
            }
        }

        private void uTF8ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormChild form = null;
            foreach (Control control in tabControl1.TabPages[tabControl1.SelectedIndex].Controls)
            {
                if (control is FormChild)
                {
                    form = (FormChild)control;
                }
            }
        }


        //用来判断是否是第一次输入
        //把打开过或者保存过的路径添加到最近打开集合中
        private void LoadPathToList(string fileName)
        {
            FileStream file = new FileStream("path.txt", FileMode.Append);
            StreamWriter write = new StreamWriter(file);
            //如果最近打开中不包含该路径,则添加
            //MessageBox.Show(fileName);
            List<string> array = new List<string>();
            foreach (string a in toolStripComboBox1.Items)
            {
                array.Add(a.Replace("\r", ""));
            }
            if (!array.Contains(fileName))
            {
                toolStripComboBox1.Items.Add(fileName);
                //向Path.txt中写入内容
                write.WriteLine(fileName);
            }
            write.Close();
        }
        //点击要打开的文件
        private void toolStripComboBox1_TextChanged(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("确定要打开这个文件吗？", "", MessageBoxButtons.OKCancel);
            if (result == DialogResult.OK)
            {
                //点击最近直接新建一个窗口
                ToolStripMenuItemNew_Click(null, null);
                FormChild form = null;
                foreach (Control control in tabControl1.TabPages[tabControl1.SelectedIndex].Controls)
                {
                    if (control is FormChild)
                    {
                        form = (FormChild)control;
                    }
                }
                //打开文件
                string path1 = toolStripComboBox1.SelectedItem.ToString().Replace("\\", "/");
                string path = path1.Replace("\r", "");

                //打开文件
                StreamReader sr = new StreamReader(path, Encoding.UTF8);
                form.textBoxNode.Text = sr.ReadToEnd();
                //textBoxNode.LoadFile(path, RichTextBoxStreamType.PlainText);
                //打开的时候将打开的文件路径写到当前窗体，并且清空记号
                string[] path_list = path.Split('/');
                form.Parent.Text = path_list[path_list.Length - 1];
                form.Text = path;

                form.toolStripLabelMake.Text = "";
                LoadPathToList(form.openFileDialog1.FileName);
                form.scanAll();
                form.updateRowIndex();
            }
        }
        //用已经保存过的txt文件内容来初始化最近打开内容
        private void InitialPathList()
        {
            FileStream file = new FileStream("path.txt", FileMode.OpenOrCreate);
            StreamReader read = new StreamReader(file);
            string[] array;
            array = read.ReadToEnd().Split('\n');
            for (int i = 0; i < array.Length - 1; i++)
            {
                if (array[i] != null)
                {
                    toolStripComboBox1.Items.Add(array[i]);
                }
                else
                {
                    break;
                }
            }
            read.Close();
        }

        private void toolStripComboBox1_TextChanged_1(object sender, EventArgs e)
        {

        }

        private void toolStripComboBoxSize_Click(object sender, EventArgs e)
        {

        }
    }
}
